
package com.jf.cloud.search.listener;

import cn.throwx.canal.gule.model.CanalBinLogResult;
import com.jf.cloud.api.product.feign.SkuStockFeignClient;
import com.jf.cloud.common.cache.constant.CacheNames;
import com.jf.cloud.common.cache.constant.ProductCacheNames;
import com.jf.cloud.common.cache.util.CacheManagerUtil;
import com.jf.cloud.common.cache.util.RedisUtil;
import com.jf.cloud.common.product.vo.search.SpuSearchUpdateVO;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.search.bo.SkuStockZoneBO;
import com.jf.cloud.search.util.EsSearchUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author zz
 * @date 2020/11/13
 */
@Component
public class SkuStockZoneCanalListener extends BaseCanalBinlogEventThrowExceptionProcessor<SkuStockZoneBO> {

    private static final Logger log = LoggerFactory.getLogger(SkuStockZoneCanalListener.class);
    @Autowired
    private SkuStockFeignClient skuStockFeignClient;

    /**
     * 更新sku分片库存
     */
    @Override
    protected void processUpdateInternal(CanalBinLogResult<SkuStockZoneBO> result) {

        SkuStockZoneBO afterData = result.getAfterData();

        // 清除缓存
        List<String> keys = new ArrayList<>();
        keys.add(CacheNames.SKU_STOCK_LIST_KEY + CacheNames.UNION + afterData.getSpuId());
        keys.add(CacheNames.SPU_ZONE_STOCK + CacheNames.UNION + afterData.getSpuId());
        keys.add(CacheNames.SPU_TOTAL_STOCK + CacheNames.UNION + afterData.getSpuId());
        keys.add(CacheNames.SKU_STOCK_KEY + CacheNames.UNION + afterData.getSkuId());
        keys.add(ProductCacheNames.SPU_ZONE + CacheNames.UNION + afterData.getSpuId());
        RedisUtil.deleteBatch(keys);

        // 更新商品库存
        ServerResponseEntity<Integer> totalStockResponse = skuStockFeignClient.getTotalStockBySpuId(afterData.getSpuId());
        if (totalStockResponse.isFail()) {
            log.error("商品id为：{}的商品库存数据异常！", afterData.getSpuId());
            return;
        }
        Integer totalStock = totalStockResponse.getData();
        log.info("商品id为：{}的商品库存更新为：{}", afterData.getSpuId(), totalStock);
        EsSearchUtil.changeSpuStockBatch(Collections.singletonList(new SpuSearchUpdateVO(afterData.getSpuId(), totalStock)));

    }
}
